package com.test.HashMapThreadUnsafe;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * Created by houjinxin on 16/9/13.
 */
public class HashMapThreadUnsafe {

    private static ExecutorService pool = Executors.newFixedThreadPool(10);

    private static HashMap<String, String> map = new HashMap<>();
//    private static ConcurrentHashMap<String, String> map = new ConcurrentHashMap<>(10);

    private static CountDownLatch count = new CountDownLatch(1);


    public static void main(String[] args) throws InterruptedException {
        for(int i=0; i<10; i++){
            final int a = i;
            pool.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        count.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    for(int j=0; j<100; j++){
                        map.put(""+j, "a"+ j);
                    }
                }
            });
        }
        count.countDown();
        System.out.println(map.size());

        List arrayList = new ArrayList(map.entrySet());

        Collections.sort(arrayList, new Comparator() {
            public int compare(Object o1, Object o2) {
                Map.Entry obj1 = (Map.Entry) o1;
                Map.Entry obj2 = (Map.Entry) o2;
                return (obj1.getKey()).toString().compareTo(obj2.getKey().toString());
            }
        });
        System.out.println(arrayList);
        stopThreadPool(pool);
    }

    public static void stopThreadPool(ExecutorService service) throws InterruptedException {
        //不在接收新的任务
        service.shutdown();
        while (true) {
//            System.out.println("线程池是否shutdown：" + (service.isShutdown() ? "已shutdown":"未shutdown"));
            System.out.println("线程池是否终止：" + (service.isTerminated() ? "已终止":"未终止"));
            if (service.isTerminated()) {
                System.out.println("结束！");
                break;
            }
            Thread.sleep(200);
        }
    }
}
